package com.seadragon.app.ksr.util;

import static com.seadragon.app.ksr.model.KsrConstants.RECENTLY_VIEWED_COOKIE_NAME;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
public class CookieUtil {
	public static JsonArray getIdListFromCookie(Cookie[] cookies) throws UnsupportedEncodingException {
		JsonArray idList = null;
		if (cookies!=null){
			for (Cookie cookie : cookies) {
				if (cookie!=null&&RECENTLY_VIEWED_COOKIE_NAME.equals(cookie.getName())){
					String jsonString= URLDecoder.decode(cookie.getValue(), "UTF-8");
					if (StringUtils.isNotEmpty(jsonString))
						idList=(JsonArray)new GsonBuilder().serializeNulls().create().fromJson(jsonString, JsonArray.class);
				}
			}
		}
		return idList;
	}	
	public static void saveCookie(String id, String type,HttpServletResponse response, Cookie[] cookies,String path)
			throws UnsupportedEncodingException {
		JsonArray idList = getIdListFromCookie(cookies);
		if (StringUtils.isNotEmpty(id)&&StringUtils.isNotEmpty(type)){
			JsonObject newEntity = new JsonObject();
			newEntity.add("id", new JsonPrimitive(id));
			newEntity.add("type", new JsonPrimitive(type));		
			idList = (idList!=null)?idList: new JsonArray();
			//if the entity is already in cookie list, remove it first, then add it on top of list
			if (!entityExist(idList, id, type)){
				idList.add(newEntity);
			}
			
			Cookie recentlyViewedCookie =  new Cookie(RECENTLY_VIEWED_COOKIE_NAME, URLEncoder.encode(idList.toString(),"UTF-8"));
			recentlyViewedCookie.setMaxAge(3600*1000*24*365);//1 year
			recentlyViewedCookie.setPath(path);
			response.addCookie(recentlyViewedCookie);
		}
	}
	private static boolean entityExist(JsonArray idList, String id, String type) {
		boolean exist = false;
		if (idList!=null){
			JsonObject idMap=null;
			for (Object object : idList) {
				idMap = (JsonObject)object;
				if (id.equals(idMap.get("id").getAsString())&&type.equals(idMap.get("type").getAsString())){
//					idList.remove(object);
					exist=true;
					break;
				}
			}
		}
		return exist;
		
	}	
}
